﻿Imports System.IO
Imports ADOConnection
Imports System.Globalization
Imports CrystalDecisions.CrystalReports.Engine

Public Class frmViewPhieuNX
    Private sdaSLNX As IDbDataAdapter
    Private sdaDPNX As IDbDataAdapter
    Private bsDPNX As BindingSource
    Private bsSLNX As BindingSource
    Private dsDataSet As DataSet
    Public mDpnx_Id As Integer = -1
    Public mSelectedIndex As Integer = -1
    Dim enumNX As enumDOITUONG = enumDOITUONG.TINHCHATNHAP
    'Chi cho phep user go duoc 1 trong 2 ky tu 'N' hoac 'X'
    Public isMaxCharNum As Boolean 'Bien dung cho event txtNX_Keydown, txtNX_Keyup

    'Public Sub CheckSystemDateFormat()
    '    'Get the Current System culture.
    '    Dim ci As CultureInfo = CultureInfo.CurrentCulture
    '    Dim dtfi As DateTimeFormatInfo = ci.DateTimeFormat
    '    Dim SystemDateTimePatterns() As String = New String(250) {}
    '    Dim i As Integer = 0
    '    For Each name As String In dtfi.GetAllDateTimePatterns("d")
    '        SystemDateTimePatterns(i) = name
    '        i += 1
    '    Next
    '    Dim myDateTimeFormat() As String = {"dd-MMM-yy", "dd-MMM-yyyy"}
    '    If (myDateTimeFormat(0).Equals(SystemDateTimePatterns(0)) Or myDateTimeFormat(1).Equals(SystemDateTimePatterns(0))) Then
    '        MessageBox.Show("Your System DateTime Format " + SystemDateTimePatterns(0) + " is OK")
    '    Else
    '        MessageBox.Show("Your System DateTime Format is: " + SystemDateTimePatterns(0) + "\n" + "Required DateTime Format: dd-MMM-yy Or dd-MMM-yyyy")
    '    End If
    'End Sub

    Private Sub frmViewPhieuNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            'Hiển thị thông tin user
            Dim sql As String = "select * from tblNHOM where NHOM_ID = " & g_User.Ban_ID
            Dim ds As DataSet = BaseDB.ExecSql_DataSet(sql)
            ToolStripStatusLabelUserInfo.Text = String.Format("Tên đăng nhập: {0} - {1}", g_User.LoginName, ds.Tables(0).Rows(0)(1))
            'ToolStripStatusLabel1.Text = "F1:Thêm   F2:Sửa  F3:Xóa  F4:Tìm kiếm  F6:In"
            ' Create columns for the items and subitems.
            lvDMPhieu.Columns.Add("Mã", 0, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("NX", 25, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("Số phiếu", 65, HorizontalAlignment.Left)
            lvDMPhieu.Columns.Add("TT", 35, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("Ngày", 70, HorizontalAlignment.Center)
            lvDMPhieu.Columns.Add("Giá trị", 110, HorizontalAlignment.Right)

            sdaDPNX = g_objConnFactory.CreateAdapter
            sdaSLNX = g_objConnFactory.CreateAdapter
            RefreshForm()
        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#Region "Events"

#Region "Draw ListView"
    Private Sub lvDMPhieu_DrawColumnHeader(ByVal sender As Object, ByVal e As DrawListViewColumnHeaderEventArgs) Handles lvDMPhieu.DrawColumnHeader
        Dim sf As New StringFormat()
        Try
            sf.Alignment = StringAlignment.Center
            ' Draw the standard header background.
            e.DrawBackground()
            ' Draw the header text.
            Dim headerFont As New Font("Courier New", 9, FontStyle.Bold)
            e.Graphics.DrawString(e.Header.Text, headerFont, Brushes.Black, e.Bounds, sf)
            'e.Graphics.DrawString(e.Header.Text, e.Font, Brushes.Black, e.Bounds, sf)
        Catch ex As Exception
        Finally
            sf.Dispose()
        End Try
    End Sub

    'Private Sub lvDMPhieu_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawListViewItemEventArgs) Handles lvDMPhieu.DrawItem

    'End Sub

    Private Sub lvDMPhieu_DrawSubItem(ByVal sender As Object, ByVal e As DrawListViewSubItemEventArgs) Handles lvDMPhieu.DrawSubItem
        Dim brText As Brush
        e.DrawBackground()
        Try
            'Neu la Selected Item thi to mau Red, nguoc lai to theo BCTH
            If (e.ItemState And DrawItemState.Selected) = DrawItemState.Selected Then
                brText = Brushes.Red
                'e.SubItem.BackColor = Color.Green
                e.Graphics.DrawRectangle(Pens.Blue, e.Bounds)
            Else
                'e.SubItem.BackColor = System.Drawing.SystemColors.Window
                Select Case Me.lvDMPhieu.Items(e.ItemIndex).SubItems(3).Text
                    Case "KH" 'Tình trạng phiếu: Kế hoạch đã xác nhận
                        brText = Brushes.Black
                    Case "KHO" 'Tình trạng phiếu: Tài chính tiền đã tiền xác nhận
                        brText = Brushes.Green
                    Case "TCT" 'Tình trạng phiếu: Tài chính tiền đã tiền xác nhận
                        brText = Brushes.Blue
                    Case "TCSL" 'Tình trạng phiếu: Tài chính số lượng đã tiền xác nhận
                        brText = Brushes.Violet
                    Case Else 'TC1, TC2, TC3, TC4
                        brText = Brushes.DarkOrange
                End Select
            End If

            ' Draw the subitem text in red to highlight it. 
            Dim sf As New StringFormat()
            'Nếu là cột tổng tiền thì set alignment = far
            If e.Header.Index = 5 Then
                sf.Alignment = StringAlignment.Far
            Else
                sf.Alignment = StringAlignment.Center
            End If

            '=================================
            'Highlight item đang chọns
            If (e.ItemState And DrawItemState.Selected) = DrawItemState.Selected Then
                e.Graphics.FillRectangle(Brushes.Yellow, e.Bounds)
            End If
            e.Graphics.DrawString(e.SubItem.Text, Me.lvDMPhieu.Font, brText, e.Bounds, sf)
        Catch ex As Exception

        End Try
    End Sub
#End Region

    Private Sub btnLoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoc.Click
        Dim frm As New frmLocPhieu
        frm.ShowDialog()
        InitListView()
        FocusListView()
    End Sub

    Private Sub lvDMPhieu_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvDMPhieu.SelectedIndexChanged
        For Each item As ListViewItem In Me.lvDMPhieu.SelectedItems
            mSelectedIndex = item.Index
            enumNX = enumDoiTuong.TINHCHATXUAT
            Select Case item.SubItems(1).Text
                Case "N"
                    lblTitle.Text = "PHIẾU NHẬP: "
                    enumNX = enumDOITUONG.TINHCHATNHAP
                Case Else
                    lblTitle.Text = "PHIẾU XUẤT: "
            End Select
            mDpnx_Id = item.SubItems(0).Text
            lblTitle.Text &= item.SubItems(2).Text + "  (Tình trạng: " + item.SubItems(3).Text & ")"

            RefreshThongTinPhieu()
            Application.DoEvents()
        Next
    End Sub

    Private Sub OpenFrmPhieuNX()
        Dim objPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        If objPhieu.BCTH = enumBCTH.KH Then
            'Nếu không phải quyền Kế hoạch và quyền Kho thì không cập nhật
            If g_User.Ban_ID <> enumPHANQUYEN.KEHOACH Then 'And g_User.Ban_ID <> enumPHANQUYEN.KHO Then
                ShowMessages("Quyền cập nhật phiếu không có.")
                Exit Sub
            End If
            'ElseIf objPhieu.BCTH = enumBCTH.KHO Then
            '    'Nếu không phải quyền Kho thì không cập nhật
            '    If g_User.Ban_ID <> enumPHANQUYEN.KHO Then
            '        'ShowMessages("Phiếu này Kho đã xác nhận. Bạn phải hủy xác nhận phiếu trước rồi mới được cập nhật phiếu")
            '        ShowMessages("Phiếu này Kho đã xác nhận. Chỉ có quyền Kho mới cập nhật phiếu này.")
            '        Exit Sub
            '    End If
            'ElseIf objPhieu.BCTH = enumPHANQUYEN.TCSL Then
            '    If g_User.Ban_ID <> enumPHANQUYEN.TCSL Then
            '        ShowMessages("Phiếu này Tài chính số lượng đã xác nhận.")
            '        Exit Sub
            '    Else
            '        ShowMessages("Tài chính sổ sách không có chức năng cập nhật phiếu.")
            '        Exit Sub
            '    End If
            'ElseIf objPhieu.BCTH = enumBCTH.TC Then
            '    If g_User.Ban_ID <> enumPHANQUYEN.TCT Then
            '        'ShowMessages("Phiếu này Tài chính tiền đã xác nhận. Bạn phải hủy xác nhận phiếu trước rồi mới được cập nhật phiếu")
            '        ShowMessages("Phiếu này Tài chính tiền đã xác nhận. Chỉ có quyền Kho mới cập nhật phiếu này.")
            '        Exit Sub
            '        'Else
            '        '    ShowMessages("Phiếu này Tài chính tiền đã xác nhận. Không thể cập nhật phiếu.")
            '        '    Exit Sub
            '    End If
            'ElseIf g_User.Ban_ID = enumPHANQUYEN.CHUNHIEMBAN Then
            '    ShowMessages("Quyền Chủ nhiệm ban không có chức năng cập nhật phiếu.")
            '    Exit Sub
        Else
            ShowMessages("Quyền cập nhật phiếu không có.")
            Exit Sub
        End If

        If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
            Dim frm As New frmPhieuNXNoiBo
            frm.fViewPhieuNX = Me
            frm.objPhieuXuat = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
            frm.objPhieuNhap = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
            frm.MdiParent = Me.MdiParent
            frm.Show()
        ElseIf CDoiTuongs.KiemTraTCNX(enumTCNX.DCSS, objPhieu.TCNX) Then
            Dim frm As New frmPhieuNXDCSS
            frm.fViewPhieuNX = Me
            frm.objPhieu = objPhieu
            frm.MdiParent = Me.MdiParent
            frm.Show()
        Else
            Dim frm As New frmPhieuNX
            frm.fViewPhieuNX = Me
            frm.objPhieu = objPhieu
            frm.MdiParent = Me.MdiParent
            frm.Show()
        End If
    End Sub

    Private Sub lvDMPhieu_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvDMPhieu.DoubleClick
        OpenFrmPhieuNX()
    End Sub

    Private Sub lvDMPhieu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lvDMPhieu.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                OpenFrmPhieuNX()
            ElseIf e.KeyCode = Keys.F6 Then
                CViewer.InPhieu(mDpnx_Id)
            ElseIf e.KeyCode = Keys.F5 Then
                RefreshForm()
            ElseIf e.KeyCode = Keys.Delete Then
                mnuItemXoa_Click(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Escape Then
                Me.Close()
            End If
        Catch ex As Exception
            ShowMessages(ex.Message.ToString)
        End Try
        
    End Sub

    Private Sub gridCTPhieu_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellDoubleClick
        Dim frm As New frmQuanLyLoHang(gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("lk").Value.ToString(), gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("makho").Value.ToString(), CInt(gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("mathang_id").Value))
        frm.ShowDialog(Me)
    End Sub

    Private Sub gridCTPhieu_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gridCTPhieu.ColumnHeaderMouseClick
        Dim count As Integer = 0
        For Each dvRow As DataGridViewRow In gridCTPhieu.Rows
            dvRow.HeaderCell.Value = (count + 1).ToString
            count += 1
        Next
    End Sub

    Private Sub Controls_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gridCTPhieu.KeyDown, gridPhieu.KeyDown, _
    btnLoc.KeyDown, txtLoc.KeyDown
        If e.KeyCode = Keys.Enter And sender Is gridCTPhieu Then
            gridCTPhieu_CellDoubleClick(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.F5 Then
            RefreshForm()
        ElseIf e.KeyCode = Keys.F6 Then
            'In
            CViewer.InPhieu(mDpnx_Id)
        ElseIf e.KeyCode = Keys.Q And e.Modifiers = Keys.Control Then
            FocusListView()
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub
#End Region

#Region "Functions"
    Public Sub InitListView()
        Dim arrDMPhieuNX As ArrayList = CPhieuNXs.GetPhieuNXList(mySqlDK)
        lblSL.Text = arrDMPhieuNX.Count
        txtLoc.Text = myShowDK

        'add data in ListView
        lvDMPhieu.Items.Clear()
        mDpnx_Id = -1
        Dim item As ListViewItem
        For Each objPhieu As CPhieuNX In arrDMPhieuNX
            item = New ListViewItem(objPhieu.DPNX_ID)
            item.SubItems.Add(objPhieu.NX)
            item.SubItems.Add(objPhieu.SOPHIEU)
            If objPhieu.KYQT > 1 Then
                'item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME + (objPhieu.KYQT - 1).ToString())
                item.SubItems.Add([Enum].GetName(GetType(enumBCTH), objPhieu.BCTH) + (objPhieu.KYQT - 1).ToString())
            Else
                'item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME)
                'If objPhieu.BCTH = enumBCTH.NONE Then
                'item.SubItems.Add("")
                'Else
                item.SubItems.Add([Enum].GetName(GetType(enumBCTH), objPhieu.BCTH))
                'End If
            End If
            item.SubItems.Add(objPhieu.NGAY.ToString(FormatDateStyle()))
            item.SubItems.Add(objPhieu.TGIATRI.ToString(FormatMoneyStyle()))
            'item.ToolTipText = CBCTHs.GetBCTH(objPhieu.BCTH).DESC
            lvDMPhieu.Items.Add(item)
        Next
        'lvDMPhieu.ShowItemToolTips = True
        'For Each objPhieu As CPhieuNX In arrDMPhieuNX
        '    item = New ListViewItem(objPhieu.DPNX_ID)
        '    item.Name = objPhieu.DPNX_ID.ToString()
        '    item.
        '    'NX
        '    Dim subItem As New ListViewItem.ListViewSubItem()
        '    subItem.Name = "NX"
        '    subItem.Text = objPhieu.NX

        '    subItem = New ListViewItem.ListViewSubItem()

        '    item.SubItems.Add(objPhieu.SOPHIEU)
        '    If objPhieu.KYQT > 1 Then
        '        item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME + (objPhieu.KYQT - 1).ToString())
        '    Else
        '        item.SubItems.Add(CBCTHs.GetBCTH(objPhieu.BCTH, objPhieu.TCSL).NAME)
        '    End If
        '    item.SubItems.Add(objPhieu.NGAY.ToString(FormatDateStyle()))
        '    item.SubItems.Add(objPhieu.TGIATRI.ToString(FormatMoneyStyle()))
        '    lvDMPhieu.Items.Add(item)
        'Next
    End Sub

    Public Sub FormatGridStyleDPNX()
        If enumNX = enumDOITUONG.TINHCHATNHAP Then
            gridPhieu.DataSource = dsDataSet.Tables("PhieuNhapInfo")
        Else
            gridPhieu.DataSource = dsDataSet.Tables("PhieuXuatInfo")
        End If

        With gridPhieu
            .AutoResizeRows()
            .Columns(0).DefaultCellStyle.BackColor = Color.Black
            .Columns(0).DefaultCellStyle.ForeColor = Color.SpringGreen
            .Columns(0).DefaultCellStyle.Font = New Font(gridPhieu.DefaultCellStyle.Font.FontFamily, 9, FontStyle.Bold)

            .Columns(1).DefaultCellStyle.ForeColor = Color.DarkBlue

            .Columns(2).DefaultCellStyle.BackColor = Color.Black
            .Columns(2).DefaultCellStyle.ForeColor = Color.SpringGreen
            .Columns(2).DefaultCellStyle.Font = New Font(gridPhieu.DefaultCellStyle.Font.FontFamily, 9, FontStyle.Bold)

            .Columns(3).DefaultCellStyle.ForeColor = Color.DarkBlue

            .Columns(0).Width = Int(gridPhieu.Width / 6) + 40
            .Columns(1).Width = gridPhieu.Columns(0).Width + 5
            .Columns(2).Width = gridPhieu.Columns(0).Width
        End With
        With gridPhieu.DefaultCellStyle
            .SelectionForeColor = Color.Yellow
        End With
        'Khoi tao gridPhieu
        If mDpnx_Id >= 0 Then
            CPhieuNXs.FillDataSetDPNX(mDpnx_Id, bsDPNX, dsDataSet)
        End If
    End Sub

    Public Sub FormatGridStyleSLNX()
        'Khoi tao gridCTPhieu
        bsSLNX.Filter = "DPNX_ID = " + mDpnx_Id.ToString
        bsSLNX.Sort = "SLNX_ID ASC"
        BindingNavigator1.BindingSource = bsSLNX
        gridCTPhieu.DataSource = bsSLNX

        For count As Integer = 0 To gridCTPhieu.RowCount - 1
            gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
        Next

        With gridCTPhieu
            .RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns.Item("slnx_id").Visible = False

            .Columns.Item("mathang_id").Visible = False
            .Columns.Item("mathang_id").Frozen = True

            .Columns.Item("dpnx_id").Visible = False

            .Columns.Item("makho").Visible = False
            .Columns.Item("makho").Frozen = True

            .Columns.Item("ma").Visible = False
            .Columns.Item("ma").Frozen = True

            .Columns.Item("code").Visible = False
            .Columns.Item("code").Frozen = True

            .Columns.Item("lk").Visible = False
            .Columns.Item("ngtton").Visible = False
            .Columns.Item("slss11").Visible = False
            .Columns.Item("slkk11").Visible = False
            .Columns.Item("sltonkh").Visible = False
            .Columns.Item("sltonth").Visible = False
            .Columns.Item("sltonss").Visible = False

            With .Columns.Item("kho")
                .Width = 70
                .HeaderText = "Kho"
                .Frozen = True
            End With

            With .Columns.Item("ten")
                .Width = 150
                .HeaderText = "Tên hàng"
                .Frozen = True
            End With

            With .Columns.Item("dvt")
                .Width = 40
                .HeaderText = "Đvt"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With

            With .Columns.Item("lo")
                .Width = 80
                .HeaderText = "Lô hàng"
            End With

            With .Columns.Item("gle")
                .HeaderText = "Giá lẻ"
                .Width = 60
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            With .Columns.Item("hansd")
                .Width = 50
                .HeaderText = "HSD"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With

            With .Columns.Item("h")
                .Width = 30
                .HeaderText = "CCL"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With

            With .Columns.Item("slkh")
                .HeaderText = "SLKH"
                .Width = 60
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            With .Columns.Item("slth")
                .HeaderText = "SLTH"
                .Width = 60
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            With .Columns.Item("thanhtien")
                .HeaderText = "Thành tiền"
                .Width = 100
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With
            With .Columns.Item("ghichu")
                .Width = 100
                .HeaderText = "Ghi chú"
            End With
        End With
    End Sub

    Public Sub RefreshThongTinPhieu()
        Try
            FormatGridStyleDPNX()
            FormatGridStyleSLNX()
            'If Me.WindowState = FormWindowState.Maximized Then
            '    gridCTPhieu.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            'End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Public Sub FocusListView()
        ControlSetFocus(lvDMPhieu)
        Try
            If lvDMPhieu.Items.Count > 0 Then
                If mSelectedIndex > 0 Then
                    lvDMPhieu.Items(mSelectedIndex).Selected = True
                Else
                    lvDMPhieu.Items(0).Selected = True
                End If
            End If
        Catch ex As Exception
            'lvDMPhieu.Items(0).Selected = True
        End Try
    End Sub

    Public Sub InitDataSet()
        bsDPNX = New BindingSource
        bsSLNX = New BindingSource
        dsDataSet = Nothing

        CPhieuNXs.CreateDataSetDPNX(dsDataSet)
        bsDPNX.DataSource = dsDataSet.Tables("PhieuNX")
        CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet)
        bsSLNX.DataSource = dsDataSet.Tables(3)
    End Sub

    Public Sub RefreshForm()
        InitDataSet()
        InitListView()
        RefreshThongTinPhieu()
        FocusListView()
    End Sub
#End Region

#Region "Context Menu"

    ''' <summary>
    ''' MenuStrip cho Admin
    ''' </summary>
    ''' <param name="bcth"></param>
    ''' <remarks></remarks>
    Private Sub ShowMnu_Admin(ByVal bcth As enumBCTH)
        With ContextMenuStrip
            ShowMnu_KeHoach(True)
            Select Case bcth
                Case enumBCTH.KH
                    .Items("ToolStripSeparatorKho").Visible = True
                    ShowMnu_Kho(True)
                Case enumBCTH.KHO
                    .Items("ToolStripSeparatorKho").Visible = True
                    ShowMnu_Kho(False)
                    .Items("ToolStripSeparatorTCSL").Visible = True
                    ShowMnu_TCSL(True)
                Case enumBCTH.TCSL
                    .Items("ToolStripSeparatorTCSL").Visible = True
                    ShowMnu_TCSL(False)
                    .Items("ToolStripSeparatorTCT").Visible = True
                    ShowMnu_TCT(True)
                Case enumBCTH.TC
                    .Items("ToolStripSeparatorTCT").Visible = True
                    ShowMnu_TCT(False)
            End Select
        End With
    End Sub

    ''' <summary>
    ''' MenuStrip cho user Kế hoạch
    ''' </summary>
    ''' <param name="value"></param>
    ''' <remarks></remarks>
    Private Sub ShowMnu_KeHoach(ByVal value As Boolean)
        With ContextMenuStrip
            .Items("mnuItemCapNhat").Visible = value
            .Items("ToolStripSeparatorDelete").Visible = value
            .Items("mnuItemXoa").Visible = value
            .Items("ToolStripSeparatorRefresh").Visible = True
            ''Refresh
            '.Items("ToolStripSeparatorRefresh").Visible = True
            '.Items("mnuItemRefresh").Visible = True
            '.Items("mnuItemInPhieu").Visible = True
            '.Items("mnuItemExcel").Visible = True
            '.Items("mnuItemLog").Visible = True
        End With
    End Sub

    ''' <summary>
    ''' MenuStrip cho user Kho
    ''' </summary>
    ''' <param name="value">True: Kho chưa xác nhận, False: Kho đã xác nhận</param>
    ''' <remarks></remarks>
    Private Sub ShowMnu_Kho(ByVal value As Boolean)
        With ContextMenuStrip
            .Items("mnuItemKhoXacNhan").Visible = value
            .Items("mnuItemKhoHuyXacNhan").Visible = Not value
            .Items("ToolStripSeparatorRefresh").Visible = True
        End With
    End Sub

    ''' <summary>
    ''' MenuStrip cho user Tài chính số lượng
    ''' </summary>
    ''' <param name="value">True: TCSL chưa xác nhận, False: TCSL đã xác nhận</param>
    ''' <remarks></remarks>
    Private Sub ShowMnu_TCSL(ByVal value As Boolean)
        With ContextMenuStrip
            .Items("mnuItemTCSLXacNhan").Visible = value
            .Items("mnuItemTCSLHuyXacNhan").Visible = Not value
            .Items("ToolStripSeparatorRefresh").Visible = True
        End With
    End Sub

    ''' <summary>
    ''' MenuStrip cho user Tài chính tiền
    ''' </summary>
    ''' <param name="value">True: TCT chưa xác nhận, False: TCT đã xác nhận</param>
    ''' <remarks></remarks>
    Private Sub ShowMnu_TCT(ByVal value As Boolean)
        With ContextMenuStrip
            .Items("mnuItemTCXacNhan").Visible = value
            .Items("mnuItemTCXacNhanI").Visible = True
            .Items("mnuItemTCXacNhanII").Visible = True
            .Items("mnuItemTCXacNhanIII").Visible = True
            .Items("mnuItemTCXacNhanIV").Visible = True
            .Items("mnuItemTCHuyXacNhan").Visible = Not value
            .Items("ToolStripSeparatorRefresh").Visible = True
        End With
    End Sub

    Private Sub lvDMPhieu_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvDMPhieu.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim ClickPoint As Point = New Point(e.X, e.Y)
            Dim objItem As ListViewItem = lvDMPhieu.GetItemAt(ClickPoint.X, ClickPoint.Y)
            Dim objPhieuNX As CPhieuNX = Nothing
            If objItem IsNot Nothing Then
                objPhieuNX = CPhieuNXs.GetPhieuByMa(objItem.Text)
            End If
            ' Convert from Tree coordinates to Screen coordinates 
            Dim ScreenPoint As Point = lvDMPhieu.PointToScreen(ClickPoint)
            ' Convert from Screen coordinates to Formc coordinates 
            Dim FormPoint As Point = Me.PointToClient(ScreenPoint)

            lvDMPhieu.ContextMenuStrip = ContextMenuStrip
            With ContextMenuStrip
                For Each item As ToolStripItem In .Items
                    item.Visible = False
                Next
                .Show(Me, FormPoint)

                'Refresh
                .Items("mnuItemRefresh").Visible = True
                .Items("mnuItemInPhieu").Visible = True
                .Items("mnuItemExcel").Visible = True
                .Items("mnuItemLog").Visible = True
            End With

            If CUsers.isAdmin(g_User.LoginName) = True Then
                ShowMnu_Admin(objPhieuNX.BCTH)
            Else
                
                Select Case CType(objPhieuNX.BCTH, enumBCTH)
                    Case enumBCTH.KH
                        Select Case CType(g_User.Ban_ID, enumPHANQUYEN)
                            Case enumPHANQUYEN.KEHOACH
                                ShowMnu_KeHoach(True)
                            Case enumPHANQUYEN.KHO
                                ShowMnu_Kho(True)
                        End Select
                    Case enumBCTH.KHO
                        Select Case CType(g_User.Ban_ID, enumPHANQUYEN)
                            'Case enumPHANQUYEN.KEHOACH
                            '    ShowMnu_KeHoach(False)
                            Case enumPHANQUYEN.KHO
                                ShowMnu_Kho(False)
                            Case enumPHANQUYEN.TCSL
                                ShowMnu_TCSL(True)
                        End Select
                    Case enumBCTH.TCSL
                        Select Case CType(g_User.Ban_ID, enumPHANQUYEN)
                            'Case enumPHANQUYEN.KEHOACH
                            '    ShowMnu_KeHoach(False)
                            Case enumPHANQUYEN.TCSL
                                ShowMnu_TCSL(False)
                            Case enumPHANQUYEN.TCT
                                ShowMnu_TCT(True)
                        End Select
                    Case enumBCTH.TC
                        Select Case CType(g_User.Ban_ID, enumPHANQUYEN)
                            'Case enumPHANQUYEN.TCSL
                            '    ShowMnu_KeHoach(False)
                            Case enumPHANQUYEN.TCT
                                ShowMnu_TCT(False)
                        End Select
                End Select
            End If
        End If
    End Sub

    Private Sub mnuItemXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemXoa.Click
        If MessageBox.Show("Bạn có chắc là xóa phiếu này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Dim objPhieu As New CPhieuNX
            objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
            'Nếu là trường hợp xóa phiếu nội bộ
            If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                'Xóa phiếu nội bộ thứ nhất
                objPhieu.Delete()

                'Xóa phiếu nội bộ còn lại
                Dim objPhieuTemp As New CPhieuNX
                If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                    objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                Else
                    objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                End If
                If objPhieuTemp.Delete() > 0 Then
                    RefreshForm()
                End If
            Else
                If objPhieu.Delete() > 0 Then
                    RefreshForm()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemRefresh.Click
        RefreshForm()
    End Sub

    Private Sub mnuItemCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemCapNhat.Click
        OpenFrmPhieuNX()
    End Sub

    Private Sub mnuItemInPhieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemInPhieu.Click
        CViewer.InPhieu(mDpnx_Id)
    End Sub

    Private Sub mnuItemTCXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles mnuItemTCXacNhan.Click, mnuItemTCXacNhanI.Click, mnuItemTCXacNhanII.Click, mnuItemTCXacNhanIII.Click, mnuItemTCXacNhanIV.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        If sender Is mnuItemTCXacNhan Then
            objPhieu.KYQT = 1 'Chua quyet toan
        ElseIf sender Is mnuItemTCXacNhanI Then
            objPhieu.KYQT = 2 'Quy I
        ElseIf sender Is mnuItemTCXacNhanII Then
            objPhieu.KYQT = 3 'Quy II
        ElseIf sender Is mnuItemTCXacNhanIII Then
            objPhieu.KYQT = 4 'Quy III
        ElseIf sender Is mnuItemTCXacNhanIV Then
            objPhieu.KYQT = 5 'Quy IV
        End If

        'Nếu TCT đã xác nhận rồi(BCTH = 2) thì chi cap nhat dpnx cho giá trị kỳ quyết toán
        If objPhieu.BCTH = enumBCTH.TC Then
            If objPhieu.Update() > 0 Then
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.KYQT = objPhieu.KYQT
                    objPhieuTemp.Update()
                End If
                RefreshForm()
            End If
        ElseIf objPhieu.BCTH = enumBCTH.TCSL Then 'Nếu phiếu đang ở tình trạng TCSL xác nhận thì TCT mới được xác nhận
            If objPhieu.TCT_XacNhan() > 0 Then
                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.XacNhan, objPhieu)
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.KYQT = objPhieu.KYQT
                    objPhieuTemp.TCT_XacNhan()
                    '==========================
                    'Write log
                    CLogs.WriteLog_PhieuNX(enumAction.XacNhan, objPhieuTemp)
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemTCHuyXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemTCHuyXacNhan.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Nếu phiếu đang ở tình trạng TCT xác nhận thì TCT mới được hủy xác nhận
        If objPhieu.BCTH = enumBCTH.TC Then
            If objPhieu.TCT_HuyXacNhan() > 0 Then
                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.HuyXacNhan, objPhieu)
                'Kiem tra neu la NX Noi bo thi cap nhat phieu con lai
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.TCT_HuyXacNhan()
                    '==========================
                    'Write log
                    CLogs.WriteLog_PhieuNX(enumAction.HuyXacNhan, objPhieuTemp)
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemTCXacNhanSL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemTCSLXacNhan.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Nếu phiếu đang ở tình trạng Kho xác nhận thì TCSL mới được xác nhận
        If objPhieu.BCTH = enumBCTH.KHO Then
            If objPhieu.TCSL_XacNhan() > 0 Then
                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.XacNhan, objPhieu)
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.TCSL_XacNhan()
                    '==========================
                    'Write log
                    CLogs.WriteLog_PhieuNX(enumAction.XacNhan, objPhieuTemp)
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemTCHuyXacNhanSL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemTCSLHuyXacNhan.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Nếu phiếu đang ở tình trạng TCSL xác nhận thì TCSL mới được hủy xác nhận
        If objPhieu.BCTH = enumBCTH.TCSL Then
            If objPhieu.TCSL_HuyXacNhan() > 0 Then
                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.HuyXacNhan, objPhieu)
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.TCSL_HuyXacNhan()
                    '==========================
                    'Write log
                    CLogs.WriteLog_PhieuNX(enumAction.HuyXacNhan, objPhieuTemp)
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemKhoXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemKhoXacNhan.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Nếu phiếu đang ở tình trạng Kế hoạch xác nhận thì Kho mới được xác nhận
        If objPhieu.BCTH = enumBCTH.KH Then
            If objPhieu.Kho_XacNhan() > 0 Then
                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.XacNhan, objPhieu)
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.Kho_XacNhan()
                    '==========================
                    'Write log
                    CLogs.WriteLog_PhieuNX(enumAction.XacNhan, objPhieuTemp)
                End If
                RefreshForm()

                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub mnuItemKhoHuyXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemKhoHuyXacNhan.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        'Nếu phiếu đang ở tình trạng Kho xác nhận thì Kho mới được hủy xác nhận
        If objPhieu.BCTH = enumBCTH.KHO Then
            If objPhieu.Kho_HuyXacNhan() > 0 Then
                CLogs.WriteLog_PhieuNX(enumAction.HuyXacNhan, objPhieu)
                'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
                If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
                    Dim objPhieuTemp As New CPhieuNX
                    'Xác nhận phiếu còn lại
                    If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
                    Else
                        objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
                    End If
                    objPhieuTemp.Kho_HuyXacNhan()
                    CLogs.WriteLog_PhieuNX(enumAction.HuyXacNhan, objPhieuTemp)
                End If
                RefreshForm()
                Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    'Private Sub mnuItemKeHoachXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemKeHoachXacNhan.Click
    '    Dim objPhieu As New CPhieuNX
    '    objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
    '    'Nếu phiếu đang ở tình trạng Kế hoạch chưa xác nhận thì Kế hoạch mới được xác nhận
    '    'If objPhieu.BCTH = enumBCTH.NONE Then
    '    If objPhieu.KeHoach_XacNhan() > 0 Then
    '        'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
    '        If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
    '            Dim objPhieuTemp As New CPhieuNX
    '            'Xác nhận phiếu còn lại
    '            If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
    '                objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
    '            Else
    '                objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
    '            End If
    '            objPhieuTemp.KeHoach_XacNhan()
    '        End If
    '        RefreshForm()
    '        Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
    '        If lvItem IsNot Nothing Then
    '            lvDMPhieu.Focus()
    '            lvItem.Selected = True
    '            lvItem.Focused = True
    '            mSelectedIndex = lvItem.Index
    '            lvItem.EnsureVisible()
    '        End If
    '    End If
    '    'End If
    'End Sub

    'Private Sub mnuItemKeHoachHuyXacNhan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemKeHoachHuyXacNhan.Click
    '    Dim objPhieu As New CPhieuNX
    '    objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
    '    'Nếu phiếu đang ở tình trạng Kế hoạch chưa xác nhận thì Kế hoạch mới được xác nhận
    '    If objPhieu.BCTH = enumBCTH.KH Then
    '        If objPhieu.KeHoach_HuyXacNhan() > 0 Then
    '            'Kiem tra neu la NX Noi bo thi cap nhat 2 phieu mot luc
    '            If CDoiTuongs.KiemTraTCNX(enumTCNX.NB, objPhieu.TCNX) Then
    '                Dim objPhieuTemp As New CPhieuNX
    '                'Xác nhận phiếu còn lại
    '                If objPhieu.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP) Then
    '                    objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, objPhieu.SOPHIEU)
    '                Else
    '                    objPhieuTemp = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, objPhieu.SOPHIEU)
    '                End If
    '                objPhieuTemp.KeHoach_HuyXacNhan()
    '            End If
    '            RefreshForm()
    '            Dim lvItem As ListViewItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
    '            If lvItem IsNot Nothing Then
    '                lvDMPhieu.Focus()
    '                lvItem.Selected = True
    '                lvItem.Focused = True
    '                mSelectedIndex = lvItem.Index
    '                lvItem.EnsureVisible()
    '            End If
    '        End If
    '    End If
    'End Sub

    Private Sub mnuItemLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemLog.Click
        Dim objPhieu As New CPhieuNX
        objPhieu = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        Dim logContent As String = ""
        If objPhieu.NX = "N" Then
            logContent = "Phiếu nhập " + objPhieu.SOPHIEU
        Else
            logContent = "Phiếu xuất " + objPhieu.SOPHIEU
        End If

        Dim frm As New frmSystemLog(logContent)
        frm.ShowDialog()
    End Sub
#End Region


    

#Region "Excel"
    Private Sub MnuItemExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuItemExcel.Click
        Dim mFileName2 As String = Application.StartupPath & "\TempPHIEUNHAPXUAT.xls"
        ToEXCEL(mFileName2)
    End Sub

    Private Sub ToEXCEL(ByVal mFileName2 As String)
        Dim objSelectedPhieu As CPhieuNX = CPhieuNXs.GetPhieuByMa(mDpnx_Id)
        Dim strSql As String
        strSql = "select * from viewNhapXuat where DPNX_ID = " & objSelectedPhieu.DPNX_ID.ToString() & _
                 " order by kho "
        Dim m_ds As DataSet
        m_ds = BaseDB.ExecSql_DataSet(strSql)

        Dim mFileName As String = Application.StartupPath & "\PHIEUNHAPXUAT.xls"

        System.IO.File.Copy(mFileName, mFileName2, True)
        Dim xlApp As Excel.Application
        Dim xlBook As Excel.Workbook
        Dim xlSheet As Excel.Worksheet
        Dim mRange As Excel.Range

        xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
        xlBook = CType(xlApp.Workbooks.Open(mFileName2), Excel.Workbook)

        xlSheet = CType(xlBook.Worksheets(1), Excel.Worksheet)

        xlSheet.Activate()
        xlSheet.Application.Visible = True

        'dau phieu

        If (objSelectedPhieu.NX = "N") Then
            xlSheet.Cells(1, 5) = "PHIẾU NHẬP KHO"
            mRange = xlSheet.Cells(1, 5)
            With mRange.Font
                .Bold = True
                .Size = 24
            End With
            xlSheet.Cells(3, 2) = "Xác Nhận Đã Nhập kho"
            xlSheet.Cells(4, 4) = "Đơn vị Giao: " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
            xlSheet.Cells(5, 4) = "Tính chất Nhập : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, objSelectedPhieu.TCNX).Ten
            xlSheet.Cells(6, 4) = "Nhập vào Kho hàng : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
            xlSheet.Cells(7, 4) = "Theo Hợp đồng : " + CHopDongs.GetHopDongByMa(objSelectedPhieu.HOPDONG).SOHOPDONG
            xlSheet.Cells(8, 4) = "Hóa đơn số : " + objSelectedPhieu.THEOLENH
            '
            xlSheet.Cells(4, 9) = "     Mã số : " + objSelectedPhieu.DVGN
            xlSheet.Cells(5, 9) = "     Mã số : " + objSelectedPhieu.TCNX
            xlSheet.Cells(6, 9) = "     Mã số : " + objSelectedPhieu.LK
            '
            xlSheet.Cells(1, 9) = "Số : " + objSelectedPhieu.SOPHIEU
            mRange = xlSheet.Cells(1, 9)
            With mRange.Font
                .Bold = True
                .Size = 11
            End With
            xlSheet.Cells(2, 9) = "Ngày " + CStr(objSelectedPhieu.NGAY.Day) + " Tháng " + CStr(objSelectedPhieu.NGAY.Month) + " Năm " + CStr(objSelectedPhieu.NGAY.Year)
            'xlSheet.Cells(2, 9) = objSelectedPhieu.NGAY.Date
            mRange = xlSheet.Cells(2, 9)
            With mRange
                .Font.Italic = True
                .Font.Size = 11
            End With
        Else
            xlSheet.Cells(1, 5) = "PHIẾU XUẤT KHO"
            mRange = xlSheet.Cells(1, 5)
            With mRange.Font
                .Bold = True
                .Size = 24
            End With
            xlSheet.Cells(3, 2) = "Xác Nhận Thanh Toán"
            xlSheet.Cells(4, 4) = "Đơn vị Nhận: " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, objSelectedPhieu.DVGN).Ten
            xlSheet.Cells(5, 4) = "Tính chất Xuất : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, objSelectedPhieu.TCNX).Ten
            xlSheet.Cells(6, 4) = "Xuất từ Kho hàng : " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, objSelectedPhieu.LK).Ten
            xlSheet.Cells(7, 4) = "Theo chỉ lệnh : " + objSelectedPhieu.THEOLENH
            xlSheet.Cells(8, 4) = "Người Nhận : " + objSelectedPhieu.NGUOIGN
            xlSheet.Cells(7, 8) = "Giá Trị Phiếu : " + objSelectedPhieu.NGAYPH
            mRange = xlSheet.Cells(7, 8)
            With mRange
                .NumberFormat = FormatDateStyle()
            End With
            xlSheet.Cells(8, 8) = "Giấy Giới Thiệu Số : " + objSelectedPhieu.GGT
            '
            xlSheet.Cells(4, 9) = "     Mã số : " + objSelectedPhieu.DVGN
            xlSheet.Cells(5, 9) = "     Mã số : " + objSelectedPhieu.TCNX
            xlSheet.Cells(6, 9) = "     Mã số : " + objSelectedPhieu.LK
            '
            xlSheet.Cells(1, 9) = "Số : " + objSelectedPhieu.SOPHIEU
            mRange = xlSheet.Cells(1, 9)
            With mRange.Font
                .Bold = True
            End With
            xlSheet.Cells(2, 9) = "Ngày " + CStr(objSelectedPhieu.NGAY.Day) + " Tháng " + CStr(objSelectedPhieu.NGAY.Month) + " Năm " + CStr(objSelectedPhieu.NGAY.Year)
            mRange = xlSheet.Cells(2, 9)
            With mRange
                .Font.Italic = True
                .Font.Size = 11
            End With

        End If

        Dim iRow0 As Integer = 16
        Dim len, i, j, stt As Integer
        Dim ten_thuoc, ma, code, lo_hang, dvt, h, hsd, ghi_chu, kho_hang As String
        Dim slth, slkh, don_gia, thanh_tien As Double

        Dim rowIndex As Integer 'Luu lai index cua dong can lam viec

        '(i chay trong ds, j chay trong excel)
        i = 0
        j = 0

        'add so thu tu vao excel
        stt = 1

        len = m_ds.Tables(0).Rows.Count

        While (i < len)
            If (i >= len) Then
                Exit While
            End If
            'Hien thi kho
            kho_hang = m_ds.Tables(0).Rows.Item(i).Item("kho")
            xlSheet.Cells(iRow0 + j, 2) = kho_hang + "  " + CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.KHO, kho_hang).Ten
            mRange = xlSheet.Cells(iRow0 + j, 2)
            With mRange
                .Font.Underline = True
                .Font.Bold = True
                .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            End With
            'insert row tuong ung voi kho
            j += 1
            mRange = xlSheet.Rows(iRow0 + j)
            mRange.Insert(Shift:=Excel.XlInsertShiftDirection.xlShiftDown)
            mRange = xlSheet.Rows(iRow0 + j)
            With mRange
                .Font.Underline = False
                .Font.Bold = False
                .HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
            End With

            'group theo Kho Hang
            While (m_ds.Tables(0).Rows.Item(i).Item("kho") = kho_hang)
                ten_thuoc = m_ds.Tables(0).Rows.Item(i).Item("ten")
                ma = m_ds.Tables(0).Rows.Item(i).Item("ma")
                code = m_ds.Tables(0).Rows.Item(i).Item("code")
                lo_hang = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("lo"))
                don_gia = m_ds.Tables(0).Rows.Item(i).Item("gle")
                dvt = m_ds.Tables(0).Rows.Item(i).Item("dvt")
                hsd = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("hansd"))
                h = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("h"))
                slth = m_ds.Tables(0).Rows.Item(i).Item("SLTH")
                slkh = m_ds.Tables(0).Rows.Item(i).Item("SLKH")
                ghi_chu = ChuanHoaChuoi(m_ds.Tables(0).Rows.Item(i).Item("GHICHU"))
                thanh_tien = m_ds.Tables(0).Rows.Item(i).Item("THANHTIEN")

                xlSheet.Cells(iRow0 + j, 1) = stt
                xlSheet.Cells(iRow0 + j, 2) = " " + ten_thuoc + Chr(10) + "  " + ma + "    " + lo_hang
                xlSheet.Cells(iRow0 + j, 3) = dvt
                xlSheet.Cells(iRow0 + j, 4) = h
                xlSheet.Cells(iRow0 + j, 5) = hsd.ToString()
                mRange = xlSheet.Cells(iRow0 + j, 5)

                'Han su dung
                'Do hsd co kieu la 01/09 nhung khi luu sang file excell no se
                'chuyen thanh 09/01/2007 nen formatnumber se la 'MM/dd'
                With mRange
                    .NumberFormat = "MM/dd"
                End With
                xlSheet.Cells(iRow0 + j, 6) = slkh
                mRange = xlSheet.Cells(iRow0 + j, 6)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(slkh) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Slkh
                xlSheet.Cells(iRow0 + j, 7) = slkh
                mRange = xlSheet.Cells(iRow0 + j, 7)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(slkh) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Don Gia
                xlSheet.Cells(iRow0 + j, 8) = don_gia
                mRange = xlSheet.Cells(iRow0 + j, 8)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(don_gia) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Thanh tien
                xlSheet.Cells(iRow0 + j, 9) = thanh_tien
                mRange = xlSheet.Cells(iRow0 + j, 9)
                With mRange
                    .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
                    If IsSoChan(thanh_tien) Then
                        .NumberFormat = "#,###"
                    Else
                        .NumberFormat = FormatQuantityStyle()
                    End If
                End With

                'Ghi chu
                xlSheet.Cells(iRow0 + j, 10) = " " + ghi_chu
                '
                i += 1
                stt += 1
                If (i >= len) Then
                    Exit While
                End If
                'insert row tuong ung voi mat hang
                j += 1
                mRange = xlSheet.Rows(iRow0 + j)
                mRange.Insert(Shift:=Excel.XlInsertShiftDirection.xlShiftDown)
            End While
        End While

        Dim iRowsCount = j
        Dim mColsCount = 10
        'AlignCenter for col1 
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 1), xlSheet.Cells(iRow0 + iRowsCount, 1))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlVAlign.xlVAlignTop
        End With
        'AlignCenter for from col3 to col5
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 3), xlSheet.Cells(iRow0 + iRowsCount, 5))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
        End With

        'AlignCenter for mColsCount
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, mColsCount), xlSheet.Cells(iRow0 + iRowsCount, mColsCount))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
            .VerticalAlignment = Excel.XlVAlign.xlVAlignTop
        End With

        'Ve line Border cho danh muc cac mat hang
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 1), xlSheet.Cells(iRow0 + iRowsCount + 4, mColsCount))
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeLeft)
            .LineStyle = Excel.XlLineStyle.xlContinuous
            .Weight = Excel.XlBorderWeight.xlThin
        End With
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeTop)
            .LineStyle = Excel.XlLineStyle.xlContinuous
            .Weight = Excel.XlBorderWeight.xlThin
        End With
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeRight)
            .LineStyle = Excel.XlLineStyle.xlContinuous
            .Weight = Excel.XlBorderWeight.xlThin
        End With

        'Aglignment cho cac col slkh,slth,gle,thanhtien
        mRange = xlSheet.Range(xlSheet.Cells(iRow0 - 1, 6), xlSheet.Cells(iRow0 + iRowsCount + 1, mColsCount - 1))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
        End With
        '
        'Merge col8 va col9 cho Tong gia tri
        '
        rowIndex = iRow0 + iRowsCount + 2 'Row cua Tong Gia tri
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 8), xlSheet.Cells(rowIndex, 9))
        With mRange
            .Merge()
            .Font.Size = 10
            .Font.Bold = True
        End With
        'Tao gach phia tren Tong gia tri
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 7), xlSheet.Cells(rowIndex, 9))
        With mRange.Borders(Excel.XlBordersIndex.xlEdgeTop)
            .LineStyle = Excel.XlLineStyle.xlDashDotDot
            .Weight = Excel.XlBorderWeight.xlThin
        End With
        'Show Tong gia tri
        xlSheet.Cells(rowIndex, 7) = "Cộng : "
        xlSheet.Cells(rowIndex, 8) = objSelectedPhieu.TGIATRI
        mRange = xlSheet.Cells(rowIndex, 8)
        With mRange
            If IsSoChan(objSelectedPhieu.TGIATRI) Then
                .NumberFormat = "#,###"
            Else
                .NumberFormat = FormatQuantityStyle()
            End If
        End With
        '
        'Phia duoi bao cao phieu nhap xuat
        rowIndex = iRow0 + iRowsCount + 6
        xlSheet.Cells(rowIndex, 2) = "Tổng cộng : " + CStr(objSelectedPhieu.SOKH) + " khoản"
        xlSheet.Cells(rowIndex, 5) = "Số kiện : " + objSelectedPhieu.SOKIEN.ToString(FormatQuantityStyle())
        xlSheet.Cells(rowIndex, 7) = "Trọng lượng : " + objSelectedPhieu.TRLUONG.ToString(FormatQuantityStyle()) + "    kg"

        xlSheet.Cells(rowIndex + 1, 2) = "Thành tiền : " + objSelectedPhieu.TGIATRI.ToString(FormatMoneyStyle()) + "   Bằng chữ : " + DoiSoRaChu(objSelectedPhieu.TGIATRI)
        xlSheet.Cells(rowIndex + 2, 2) = "Đã nhận đủ hàng     Ngày    tháng    năm      "
        'Chinh lai font chu cho cac COL 2 Tong cong, So kien, Trong luong, Thanhtien, Da nhan du hang
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 2), xlSheet.Cells(rowIndex + 2, 7))
        With mRange
            .Font.Size = 9
        End With

        'Tao col va show data cho dong "Thu Kho   Nguoi Giao nhan     Nguoi viet phieu   Thu truong don vi"
        rowIndex = iRow0 + iRowsCount + 10
        xlSheet.Range(xlSheet.Cells(rowIndex, 2), xlSheet.Cells(rowIndex, 10)).Merge()
        xlSheet.Range(xlSheet.Cells(rowIndex, 2), xlSheet.Cells(rowIndex, 10)).Font.Bold = True
        xlSheet.Cells(rowIndex, 2) = "Thủ Kho                               Người Giao             Người Viết Phiếu               Thủ Trưởng Đơn Vị"
        rowIndex = iRow0 + iRowsCount + 14
        xlSheet.Cells(rowIndex, 3) = objSelectedPhieu.NGUOIGN
        xlSheet.Cells(rowIndex, 6) = objSelectedPhieu.NGUOIVP
        xlSheet.Range(xlSheet.Cells(rowIndex, 6), xlSheet.Cells(rowIndex, 7)).Merge()
        mRange = xlSheet.Range(xlSheet.Cells(rowIndex, 1), xlSheet.Cells(rowIndex, mColsCount))
        With mRange
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlHAlign.xlHAlignCenter
        End With

        xlBook.Save()
        xlApp.ActiveWindow.Visible = False
        xlApp.Windows(1).Activate()
    End Sub
#End Region

    Private Sub txtNX_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtNX.KeyDown
        isMaxCharNum = False
        If e.KeyCode = Keys.Enter Then
            Dim lvItem As ListViewItem
            Dim obj As CPhieuNX
            If txtNX.Text = "N" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, txtSoPhieu.Text)
            ElseIf txtNX.Text = "X" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, txtSoPhieu.Text)
            Else
                ShowMessages("Loại phiếu không hợp lệ")
                Exit Sub
            End If
            If obj IsNot Nothing Then
                mDpnx_Id = obj.DPNX_ID
                lvItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        Else
            If txtNX.Text.Length = 1 Or (e.KeyCode <> Keys.N And e.KeyCode <> Keys.X) Then
                If e.KeyCode <> Keys.Back Then
                    isMaxCharNum = True
                End If
            End If
        End If
    End Sub

    Private Sub txtNX_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNX.KeyPress
        If isMaxCharNum = True Then
            e.Handled = True
        Else
            e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString(), VbStrConv.Uppercase))
        End If
    End Sub

    Private Sub txtSoPhieu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSoPhieu.KeyDown
        If e.KeyCode = Keys.Enter Then
            Dim lvItem As ListViewItem
            Dim obj As CPhieuNX
            If txtNX.Text = "N" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, txtSoPhieu.Text)
            ElseIf txtNX.Text = "X" Then
                obj = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATXUAT, txtSoPhieu.Text)
            Else
                ShowMessages("Loại phiếu không hợp lệ")
                Exit Sub
            End If
            If obj IsNot Nothing Then
                mDpnx_Id = obj.DPNX_ID
                lvItem = lvDMPhieu.FindItemWithText(mDpnx_Id)
                If lvItem IsNot Nothing Then
                    lvDMPhieu.Focus()
                    lvItem.Selected = True
                    lvItem.Focused = True
                    mSelectedIndex = lvItem.Index
                    lvItem.EnsureVisible()
                End If
            End If
        End If
    End Sub

    Private Sub txtSoPhieu_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSoPhieu.KeyPress
        'Viet hoa cac ky tu go
        e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString(), VbStrConv.Uppercase))
    End Sub

    
End Class